package main.java.servlet;

import main.java.servlet.test.Test;
import main.java.utils.Student;
import main.java.utils.StudentManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * web 3.0版本后可以使用注解@WebServlet来代替web.xml配置
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        String path = req.getServletPath();
        String user = req.getParameter("user");
        // 根据path来调用具体的业务方法
        if(path.equals("/login.do")){
            doLogin(req,res);
        }else if(path.equals("/delStu.do")){
            String id = req.getParameter("id");
            int stuId = Integer.parseInt(id);
            deleteStu(stuId,res);
        }
    }

    // 根据id删除学生信息
    private void deleteStu(Integer id, HttpServletResponse res) throws IOException {
        System.out.println("1111");
        res.setContentType("text;charset=UTF-8");

        PrintWriter out = res.getWriter();
        out.print("success");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        System.out.println("doGet init");
    }

    protected void doLogin(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        System.out.println(req.getParameter("user"));
        String user = req.getParameter("user");
        String password = req.getParameter("password");
        // 是否勾选记住密码复选框
        String check = req.getParameter("check"); // 如果你勾选了，那么它的值应该是on,如果不勾选的话check应该是null
        if(user != null && password != null && "on".equals(check)){
            Cookie userCookie = new Cookie("user", URLEncoder.encode(user, "utf-8"));// cookie中文存储记得编码
            Cookie passwordCookie = new Cookie("password",password);
            userCookie.setMaxAge(60); //设置cookie有效期为1小时
            passwordCookie.setMaxAge(60); //设置cookie有效期为1小时
            res.addCookie(userCookie);
            res.addCookie(passwordCookie);
        }
        // 登录后跳转
        StudentManager studentManager = new StudentManager();
        List<Student> list = studentManager.findAll();
        req.setAttribute("stu", list);
        req.getRequestDispatcher("/stuList.jsp").forward(req, res);
    }

}
